from pymongo import MongoClient
import traceback
from app.utils.logger import get_logger

logger = get_logger('mongodb')

class MongoDB:
    """MongoDB数据库连接管理类"""
    
    def __init__(self):
        self.client = None
        self.db = None
    
    def init_app(self, app):
        """初始化MongoDB连接"""
        try:
            mongo_uri = app.config.get('MONGO_URI')
            mongo_db = app.config.get('MONGO_DB')
            
            logger.info(f"尝试连接MongoDB: {mongo_uri}/{mongo_db}")
            self.client = MongoClient(mongo_uri, serverSelectionTimeoutMS=5000)
            # 添加连接测试
            self.client.admin.command('ping')
            self.db = self.client[mongo_db]
            logger.info(f"MongoDB连接成功: {mongo_uri}/{mongo_db}")
            
            # 创建索引以提高查询效率
            self.create_indexes()
            
        except Exception as e:
            logger.error(f"MongoDB连接失败: {str(e)}")
            logger.error(f"MongoDB连接错误详情: {traceback.format_exc()}")
            # 如果MongoDB连接失败，仍然可以使用文件存储作为备份
    
    def create_indexes(self):
        """创建必要的索引"""
        try:
            if self.db is not None:
                # 为环境数据集合创建索引
                env_collection = self.db['environment_data']
                # 创建设备ID和时间戳的复合索引
                env_collection.create_index([('deviceId', 1), ('timestamp', -1)])
                logger.info("MongoDB索引创建成功")
        except Exception as e:
            logger.error(f"创建MongoDB索引失败: {str(e)}")
            logger.error(f"索引创建错误详情: {traceback.format_exc()}")
    
    def get_collection(self, collection_name):
        """获取指定的集合"""
        if self.db is not None:
            try:
                # 测试集合是否可用
                collection = self.db[collection_name]
                # 执行一个简单的操作来验证集合是否可用
                collection.find_one({}, {'_id': 1})
                return collection
            except Exception as e:
                logger.error(f"获取MongoDB集合 {collection_name} 失败: {str(e)}")
                logger.error(f"集合访问错误详情: {traceback.format_exc()}")
                return None
        logger.warning(f"MongoDB数据库连接不可用，无法获取集合 {collection_name}")
        return None

# 创建MongoDB实例
mongodb = MongoDB()

def init_mongodb(app):
    """初始化MongoDB连接"""
    mongodb.init_app(app)
    return mongodb